﻿import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { HubConnection, HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
import { EnumNotificationType, SignalrToken } from "@/enums/business/signalrToken.enum";

export const useSignalRStore = defineStore("signalr", () => {
  // 状态
  const connection = ref<HubConnection | null>(null);
  const connectionUrl = import.meta.env.VITE_APP_API_URL + import.meta.env.VITE_APP_SIGNALR_HUB; // 替换为实际的Hub地址
  const messages = ref<{ id: number; user: string; text: string }[]>([]);
  const connectionState = ref<string>("Disconnected");
  const error = ref<string | null>(null);

  // 初始化连接
  const initialize = async () => {
    try {
      console.log("初始化SignalR连接...", connectionUrl);
      connection.value = new HubConnectionBuilder()
        .withUrl(connectionUrl)
        .withAutomaticReconnect()
        .configureLogging(LogLevel.Information)
        .build();

      // 监听连接状态变化
      connection.value.onclose((err) => {
        connectionState.value = "Disconnected";
        error.value = err?.message || "连接已关闭";
      });

      connection.value.onreconnecting((err) => {
        connectionState.value = "Reconnecting";
        error.value = err?.message || "正在重连...";
      });

      connection.value.onreconnected(() => {
        connectionState.value = "Connected";
        error.value = null;
      });

      // 启动连接
      await connection.value.start();
      connectionState.value = "Connected";
      error.value = null;
    } catch (err) {
      connectionState.value = "Disconnected";
      error.value = (err as Error).message;
      console.error("SignalR连接失败:", err);
    }
  };

  // 订阅消息
  function subscribe(token: SignalrToken, callback: (...args: any[]) => any) {
    if (connection.value) {
      connection.value.on(token, callback);
    }
  }

  // 断开连接
  const disconnect = async () => {
    if (connection.value) {
      try {
        await connection.value.stop();
        connectionState.value = "Disconnected";
        connection.value = null;
      } catch (err) {
        error.value = (err as Error).message;
        console.error("断开连接失败:", err);
      }
    }
  };

  // 计算属性：是否已连接
  const isConnected = computed(() => connectionState.value === "Connected");

  // 生命周期监听：组件卸载时断开连接
  watch(connection, (newVal, oldVal) => {
    if (oldVal && !newVal) {
      disconnect();
    }
  });

  return {
    connection,
    messages,
    connectionState,
    error,
    isConnected,
    initialize,
    disconnect,
    subscribe,
  };
});

/*signalrStore.subscribe(
  SignalrToken.Notification,
  (type: EnumNotificationType, msg: string, time: string) => {
    console.log("subscribe", type, msg, time);
  }
);

signalrStore.subscribe(
  SignalrToken.SensorVal,
  (sensorCode: string, val: number, time: string) => {
    console.log("subscribe", sensorCode, val, time);
  }
);*/
